package com.zy.explore.client.infrastructure.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 建类说明：Druid数据库连接池的配置
 *
 * @author 🇨🇳中国印🇨🇳
 * @date 2022年04月17日 02:38:46
 */
@Configuration
@ConditionalOnProperty(DruidConfig.PREFIX)
public class DruidConfig {

    public static final String PREFIX = "spring.datasource";

    @Bean
    @ConfigurationProperties(prefix = PREFIX)
    public DruidDataSource druid(){
        return  new DruidDataSource();
    }

    /**
     * 方法说明：配置 Druid 监控管理后台的Servlet
     * 内置 Servlet 容器时没有web.xml文件，所以使用 Spring Boot 的注册 Servlet 方式
     *
     * @return {@link ServletRegistrationBean }
     */
    @Bean
    public ServletRegistrationBean<StatViewServlet> statViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        // 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet 的父类 com.alibaba.druid.support.http.ResourceServlet 中找到
        Map<String,String> initParams = new HashMap<>();

        // 如果启用账号密码登录监控页，则增加此配置
        // initParams.put("loginUsername","admin");
        // initParams.put("loginPassword","123456");

        // 默认就是允许所有访问
        initParams.put("allow","");

        // deny：Druid 后台拒绝谁访问，表示禁止此ip访问
        // initParams.put("deny","192.168.10.132");

        // 设置是否允许重置
        initParams.put("resetEnable", "false");
        bean.setInitParameters(initParams);
        return bean;
    }

    /**
     * 方法说明：配置一个web监控的filter
     *
     * @return {@link FilterRegistrationBean }
     */
    @Bean
    public FilterRegistrationBean<WebStatFilter> webStatFilter(){
        FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new WebStatFilter());
        Map<String,String> initParams = new HashMap<>();
        initParams.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParams);
        bean.setUrlPatterns(Collections.singletonList("/*"));
        return  bean;
    }
}

